﻿using IQIGame.Onigao.GamePlay;

namespace IQIGame.Onigao.Logic
{
    public class DeadComponent : TComponent
    {
        public Unit unit { get; private set; }
        public Unit attacker { get; private set; }

        public bool realDead;
        
        public bool canRelive = true;

        protected override void OnDispose()
        {
        }

        public void Initialize(Unit attacker, bool deadNow)
        {
            this.attacker = attacker;
            if (deadNow)
            {
                this.Dead();
            }
        }

        public void Dead()
        {
            this.unit.battle.playCtrl.triggerCtrl.Broadcast(EBattleTriggerType.Battle_UnitDie, this.unit, this.attacker);
            if (this.unit.battle != null)
            {
                var rResultCtrl = this.unit.battle.playCtrl.resultCtrl;
                var rPOD = BattleUpdateFactory.CreateUnitDead(this.unit.GUID, this.attacker.GUID, false);
                rResultCtrl.Add(rPOD);
            }

            this.unit.ClearHoldMap();
            
            var rBuffComp = this.unit.GetComponent<BuffComponent>(ETComponentType.BuffComponent);
            rBuffComp?.OnDead();
            
            var rSkillComp = this.unit.GetComponent<SkillComponent>(ETComponentType.SkillComponent);
            rSkillComp?.OnDead();
            
            this.realDead = true;
        }

        public void Relive()
        {
            if (!this.canRelive)
            {
                return;
            }
            this.attacker = null;
            
            if (this.unit.battle != null)
            {
                var rResultCtrl = this.unit.battle.playCtrl.resultCtrl;
                var rPOD = BattleUpdateFactory.CreateUnitDead(this.unit.GUID, 0, true);
                rResultCtrl.Add(rPOD);
            }
            var rBuffComp = this.unit.GetComponent<BuffComponent>(ETComponentType.BuffComponent);
            rBuffComp?.Relive();
            
            var rSkillComp = this.unit.GetComponent<SkillComponent>(ETComponentType.SkillComponent);
            rSkillComp?.Relive();
        }

        public override void OnCreate(TEntity entity)
        {
            this.unit = entity as Unit;
        }

        public void TriggerRealDead()
        {
        }
    }
}